package org.zch.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.zch.service.FileService;
import java.io.File;
import java.io.IOException;


/**
 * title
 *
 * @Author 刘新
 * @Date 2024/1/3 16:46
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${file.path:/home/downloads}")
    private String filePath;

    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 创建文件对象
        File targetFile = new File(filePath + "/" + fileName);
        try {
            // 将文件保存到指定目录
            file.transferTo(targetFile);
            return "文件上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }

    /**
     * 根据文件名删除文件
     * @param fileName 文件名
     * @return 0 成功删除
     *          -1 目录不存在
     *          -2 文件不存在
     *          -3 删除失败
     */
    @Override
    public Integer deleteByName(String fileName) {
        Integer result = 0;
        String directoryPath = filePath;
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            System.out.println("找不到目录");
            result = -1;
        }else {
            File[] files = directory.listFiles();
            if (files == null || files.length == 0) {
                System.out.println("文件不存在");
                result =  -2;
            }else {
                boolean fileFound = false;
                for (File file : files) {
                    if (file.getName().equals(fileName)) {
                        if (file.delete()) {
                            System.out.println("成功删除文件：" + fileName);
                            fileFound = true;
                        } else {
                            System.out.println("删除文件失败：" + fileName);
                            result = -3;
                        }
                        break;
                    }
                }

                if (!fileFound) {
                    System.out.println("文件不存在");
                    result = -2;

                }
            }
        }
        return result;
    }
}
